package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.search.aggregations.metrics.max.InternalMax;
import org.elasticsearch.search.aggregations.metrics.min.InternalMin;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName: AggsTvsSearch
 * @author: BANG
 * @Date: 2020/01/15 13:56
 * @Version: 1.0
 * @Modified By:
 * @Desc:
 * GET /tvs/sales/_search
 * {
 *    "size" : 0,
 *    "aggs": {
 *       "colors": {
 *          "terms": {
 *             "field": "color"
 *          },
 *          "aggs": {
 *             "avg_price": { "avg": { "field": "price" } },
 *             "min_price" : { "min": { "field": "price"} },
 *             "max_price" : { "max": { "field": "price"} },
 *             "sum_price" : { "sum": { "field": "price" } }
 *          }
 *       }
 *    }
 * }
 */
public class AvgMaxTvsSearch {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .addAggregation(AggregationBuilders.terms("colors").field("color")
                        .subAggregation(AggregationBuilders.avg("avg_price").field("price"))
                        .subAggregation(AggregationBuilders.min("min_price").field("price"))
                        .subAggregation(AggregationBuilders.max("max_price").field("price"))
                        .subAggregation(AggregationBuilders.sum("sum_price").field("price"))
                                )
                .setSize(0)
                .get();


        Aggregations aggregations = searchResponse.getAggregations();
        Terms  group_by_color = aggregations.get("colors");
        for (Terms.Bucket entry : group_by_color.getBuckets()) {
            Aggregations entryAggregations = entry.getAggregations();
            InternalAvg avg_price = entryAggregations.get("avg_price");
            String valueAsString = avg_price.getValueAsString();
            System.err.println(String.format("key:{%s} doc_count:{%s} color_avg_price:{%s} ",entry.getKey(),entry.getDocCount(),valueAsString));
            InternalMin min_price = entryAggregations.get("min_price");
            InternalMax max_price = entryAggregations.get("max_price");
            InternalSum sum_price = entryAggregations.get("sum_price");
            System.err.println(String.format("min_price:{%s} max_price:{%s} sum_price:{%s} ",
                    min_price.getValueAsString(),max_price.getValueAsString(),sum_price.getValueAsString()));
            System.err.println("=====================");
        }

//        Map<String, Aggregation> asMap = aggregations.getAsMap();
//        for (Map.Entry<String, Aggregation> entry : asMap.entrySet()) {
//            System.out.println(entry.getKey());
//            Aggregation aggregation = entry.getValue();
//            StringTerms terms = (StringTerms) aggregation;
//            List<Terms.Bucket> bucketList = terms.getBuckets();
//            for (Terms.Bucket bucket : bucketList) {
//                System.out.println(bucket.getKeyAsString()+"="+bucket.getDocCount());
//            }
//
//        }
//
//
//        List<Aggregation> aggregationList = aggregations.asList();
//        for (Aggregation aggregation : aggregationList) {
//            String name = aggregation.getName();
//            System.out.println(name);
//            StringTerms terms = (StringTerms) aggregation;
//            List<Terms.Bucket> bucketList = terms.getBuckets();
//            for (Terms.Bucket bucket : bucketList) {
//                System.out.println(bucket.getKeyAsString() + "=" + bucket.getDocCount());
//            }
//
//        }

        client.close();

    }
}
